<script lang="tsx">
import { defineComponent, onMounted, reactive, ref, toRefs } from 'vue';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { Search, SvgNoDataIcon } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElDialog,
  ElIcon,
  ElInput,
  ElPagination,
  ElTabPane,
  ElTabs,
} from 'element-plus';

import { getUserMessageApi, type SystemAnnouncementItem } from '#/api/personal';
import { useMessage } from '#/hooks/useMessage';

export default defineComponent({
  name: 'UserMessage',
  setup() {
    const total = ref(0);
    const tableLoading = ref(false);
    const tableData = ref<SystemAnnouncementItem[]>([]);
    const searchKeyword = ref('');
    const activeTab = ref('all');

    // 弹窗相关状态
    const dialogVisible = ref(false);
    const currentMessage = ref<SystemAnnouncementItem>({} as SystemAnnouncementItem);
    const currentMessageIndex = ref(0);

    const pageData = reactive({
      curPage: 1,
      pageSize: 10,
    });

    // Tab选项
    const tabOptions = [
      { label: $t('userMessage.all'), value: 'all' },
      { label: $t('userMessage.systemNotice'), value: 'system' },
      { label: $t('userMessage.upgradeNotice'), value: 'upgrade' },
      { label: $t('userMessage.examNotice'), value: 'exam' },
    ];

    const { fetchUnreadCount } = useMessage();

    const getUserMessage = () => {
      const { curPage, pageSize } = toRefs(pageData);
      
      // 根据新接口文档构造参数
      const params = {
        type: activeTab.value === 'all' ? undefined : activeTab.value as 'system' | 'upgrade' | 'exam',
        keyWord: searchKeyword.value || undefined,
        curPage: curPage.value,
        pageSize: pageSize.value,
      };

      tableLoading.value = true;

      // 调用真实API
      getUserMessageApi(params)
        .then((res) => {
          const { data, pageInfo } = res;
          tableData.value = data || [];
          total.value = pageInfo?.totalRows || 0;
        })
        .catch((error) => {
          console.error('API请求失败:', error);
          tableData.value = [];
          total.value = 0;
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    const handleSizeChange = (val: number) => {
      pageData.pageSize = val;
      pageData.curPage = 1;
      getUserMessage();
    };

    const handleCurrentChange = (val: number) => {
      pageData.curPage = val;
      getUserMessage();
    };

    const handleTabChange = (tabName: number | string) => {
      activeTab.value = String(tabName);
      pageData.curPage = 1;
      getUserMessage();
    };

    const handleSearch = () => {
      pageData.curPage = 1;
      getUserMessage();
    };

    // 获取消息类型标签样式
    const getMessageTypeClass = (type: string) => {
      switch (type) {
        case 'exam': {
          return 'exam-notice';
        }
        case 'system': {
          return 'system-notice';
        }
        case 'upgrade': {
          return 'upgrade-notice';
        }
        default: {
          return 'default-notice';
        }
      }
    };

    // 获取消息类型文本
    const getMessageTypeText = (type: string) => {
      switch (type) {
        case 'exam': {
          return $t('userMessage.examNotice');
        }
        case 'system': {
          return $t('userMessage.systemNotice');
        }
        case 'upgrade': {
          return $t('userMessage.upgradeNotice');
        }
        default: {
          return $t('userMessage.notice');
        }
      }
    };

    // 格式化时间
    const formatTime = (timestamp: number | string) => {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      });
    };

    // 处理消息点击（本地标记为已读）
    const handleMessageClick = async (item: any) => {
      if (!item.isRead && item.id) {
        // 仅更新本地状态
        item.isRead = true;
        // 刷新未读消息数量
        fetchUnreadCount();
        console.log('本地标记消息为已读:', item.id);
      }
    };

    // 处理消息标题点击，打开详情弹窗
    const handleTitleClick = async (item: any, index: number) => {
      currentMessage.value = item;
      currentMessageIndex.value = index;
      dialogVisible.value = true;
      await handleMessageClick(item); // 同时标记为已读
    };

    // 关闭弹窗
    const handleCloseDialog = () => {
      dialogVisible.value = false;
    };

    // 上一条消息
    const handlePrevMessage = async () => {
      if (currentMessageIndex.value > 0) {
        currentMessageIndex.value--;
        const message = tableData.value[currentMessageIndex.value];
        if (message) {
          currentMessage.value = message;
          await handleMessageClick(currentMessage.value);
        }
      }
    };

    // 下一条消息
    const handleNextMessage = async () => {
      if (currentMessageIndex.value < tableData.value.length - 1) {
        currentMessageIndex.value++;
        const message = tableData.value[currentMessageIndex.value];
        if (message) {
          currentMessage.value = message;
          await handleMessageClick(currentMessage.value);
        }
      }
    };

    // 页面加载时获取数据
    onMounted(() => {
      getUserMessage();
    });

    return () => (
      <div class="user-message-container">
        {/* Tab切换和搜索 */}
        <div class="header-section">
          <ElTabs
            class="message-tabs"
            onTabChange={handleTabChange}
            v-model={activeTab.value}
          >
            {tabOptions.map((tab) => (
              <ElTabPane key={tab.value} label={tab.label} name={tab.value} />
            ))}
          </ElTabs>

          <div class="search-section">
            <ElInput
              class="search-input"
              clearable
              modelValue={searchKeyword.value}
              onClear={handleSearch}
              onKeydown={(e: any) => {
                if (e.key === 'Enter') {
                  handleSearch();
                }
              }}
              onUpdate:modelValue={(val: string) => (searchKeyword.value = val)}
              placeholder={$t('userMessage.searchPlaceholder')}
            >
              {{
                suffix: () => (
                  <span style="cursor: pointer" onClick={handleSearch}>
                    <ElIcon>
                      <Search />
                    </ElIcon>
                  </span>
                ),
              }}
            </ElInput>
          </div>
        </div>

        {/* 消息列表 */}
        <div class="message-list" v-loading={tableLoading.value}>
          {tableData.value.length === 0 ? (
            <div class="w-full h-full flex flex-col items-center justify-center">
              <VbenIcon icon={SvgNoDataIcon} class={`w-[200px] h-[200px] fill-transparent mb-[10px]`} />
              <span class="text-[14px] leading-[22px] text-[#595959]">
                {$t('common.emptyTxt')}
              </span>
            </div>
          ) : (
            <div class="message-items">
              {tableData.value.map((item: any, index: number) => (
                <div
                  class={['message-item']}
                  key={item.id || index}
                  onClick={() => {
                    handleMessageClick(item);
                  }}
                >
                  {/* 消息类型标签 */}
                  <div
                    class={['message-type-tag', getMessageTypeClass(item.type)]}
                  >
                    <span class="text-center text-[14px] leading-[18px] w-[28px]">
                      {getMessageTypeText(item.type)}
                    </span>
                  </div>

                  {/* 消息内容 */}
                  <div class="message-content">
                    <div class="message-header">
                      <div class="message-time">
                        {formatTime(item.createTime)}
                      </div>
                    </div>
                    <div
                      class="message-title"
                      onClick={(e: Event) => {
                        e.stopPropagation();
                        handleTitleClick(item, index);
                      }}
                    >
                      {item.title}
                    </div>
                    <div class="message-desc" innerHTML={item.content}></div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 分页器 */}
        <div class="pagination-wrapper">
          <ElPagination
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            onCurrent-change={handleCurrentChange}
            onSize-change={handleSizeChange}
            page-sizes={[5, 10, 20, 50]}
            total={total.value}
            v-model:current-page={pageData.curPage}
            v-model:page-size={pageData.pageSize}
          />
        </div>

        {/* 消息详情弹窗 */}
        <ElDialog
          class="message-detail-dialog"
          onClose={handleCloseDialog}
          title={$t('userMessage.noticeDetail')}
          v-model={dialogVisible.value}
          v-slots={{
            footer: () => (
              <div class="dialog-footer">
                <div class="nav-buttons">
                  <ElButton
                    disabled={currentMessageIndex.value === 0}
                    onClick={handlePrevMessage}
                  >
                    {$t('userMessage.previousMessage')}
                  </ElButton>
                  <ElButton
                    disabled={
                      currentMessageIndex.value === tableData.value.length - 1
                    }
                    onClick={handleNextMessage}
                  >
                    {$t('userMessage.nextMessage')}
                  </ElButton>
                  <ElButton onClick={handleCloseDialog} type="primary">
                    {$t('userMessage.close')}
                  </ElButton>
                </div>
              </div>
            ),
          }}
          width="800px"
        >
          <div class="dialog-content">
            <div class="dialog-message-item">
              {/* 消息类型标签 - 参照外面卡片样式 */}
              <div
                class={[
                  'dialog-message-type-tag',
                  getMessageTypeClass(currentMessage.value.type),
                ]}
              >
                <span class="text-center text-[14px] leading-[18px] w-[28px]">
                  {getMessageTypeText(currentMessage.value.type)}
                </span>
              </div>

              {/* 消息内容区域 */}
              <div class="dialog-message-content">
                <div class="dialog-message-header">
                  <div class="dialog-message-time">
                    {formatTime(currentMessage.value.createTime)}
                  </div>
                </div>
                <h3 class="dialog-message-title">
                  {currentMessage.value.title}
                </h3>
                <div
                  class="dialog-message-full-content"
                  innerHTML={currentMessage.value.content}
                ></div>
              </div>
            </div>
          </div>
        </ElDialog>
      </div>
    );
  },
});
</script>

<style lang="less" scoped>
.user-message-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: 100vh;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;

  .header-section {
    flex-shrink: 0;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 8px 24px 0;
    background: white;

    .el-tabs {
      --el-tabs-header-height: 41px;
    }

    .message-tabs {
      flex: 1;
      --el-border-color-light: #DCDFE6;

      :deep(.el-tabs__header) {
        margin: 0;

        .el-tabs__item {
          width: 96px;
          font-size: 16px;
          color: #595959;
          padding: 0;

          &.is-active {
            color: #0067D1;
            border-bottom: 1px solid #0067D1;
          }
        }
      }
    }

    .search-section {
      width: 300px;
      position: absolute;
      right: 20px;
      top: 12px;

      .search-input {
        width: 100%;
      }
    }
  }

  .message-list {
    flex: 1 1 0;
    padding: 12px 24px;
    overflow-y: auto;
    min-height: 0;

    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 300px;
    }

    .message-items {
      .message-item {
        display: flex;
        background: white;
        padding: 16px 20px 26px 24px;
        border-bottom: 1px solid #e4e7ed;
        transition: all 0.3s ease;

        .message-type-tag {
          flex-shrink: 0;
          width: 50px;
          height: 50px;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-wrap: wrap;
          border-radius: 50%;
          font-size: 16px;
          margin-right: 16px;
          padding: 5px;
          text-align: center;

          &.system-notice {
            background-color: rgba(215, 221, 225, 1);
            color: rgba(85, 114, 131, 1);
            border: none;
          }

          &.exam-notice {
            background-color: rgba(242, 225, 204, 1);
            color: rgba(192, 116, 24, 1);
            border: none;
          }

          &.upgrade-notice {
            background-color: rgba(230, 247, 255, 1);
            color: rgba(24, 144, 255, 1);
            border: none;
          }

          &.default-notice {
            background-color: #f6f6f6;
            color: #666;
            border: 1px solid #d9d9d9;
          }
        }

        .message-content {
          flex: 1;

          .message-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;

            .message-time {
              font-size: 14px;
              color: rgba(25, 25, 25, 1);
            }

            .unread-badge {
              font-size: 10px;
              color: #409eff;
              background: #e6f7ff;
              border: 1px solid #91d5ff;
              border-radius: 8px;
              padding: 2px 6px;
              font-weight: 500;
            }
          }

          .message-title {
            font-size: 14px;
            font-weight: 600;
            color: rgba(25, 25, 25, 1);
            margin-bottom: 12px;
            cursor: pointer;

            &:hover {
              color: #0067d1;
              text-decoration: underline;
            }
          }

          .message-desc {
            font-size: 14px;
            line-height: 22px;
            max-height: 110px;
            overflow: hidden;
          }
        }
      }
    }
  }

  .pagination-wrapper {
    flex-shrink: 0;
    padding: 12px 24px 24px 24px;
    background: white;

    .pagination {
      :deep(.el-pagination__total) {
        margin-right: 10px;
      }

      &.el-pagination {
        width: 100%;
        --el-pagination-button-height: 28px;
        justify-content: end;
      }

      :deep(.el-pagination__total) {
        margin-left: auto;
      }

      :deep(.el-pagination__sizes) {
        margin-right: auto;

        .el-select__wrapper {
          min-height: 28px;
        }
      }

      :deep(.el-pagination__jump) {
        margin-left: 30px;

        .el-input {
          --el-input-height: 28px;
        }
      }
    }
  }
}

// 弹窗样式
:deep(.message-detail-dialog) {
  .el-dialog__header {
    padding: 20px 24px 16px;
    border-bottom: 1px solid #e4e7ed;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 24px;
    max-height: 60vh;
    overflow-y: auto;
  }

  .el-dialog__footer {
    padding: 16px 24px 20px;
    border-top: 1px solid #e4e7ed;
  }
}

.dialog-content {
  .dialog-message-item {
    display: flex;
    background: white;

    .dialog-message-type-tag {
      flex-shrink: 0;
      width: 60px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-wrap: wrap;
      border-radius: 50%;
      font-size: 16px;
      margin-right: 20px;
      padding: 5px;
      text-align: center;

      &.system-notice {
        background-color: rgba(215, 221, 225, 1);
        color: rgba(85, 114, 131, 1);
        border: none;
      }

      &.exam-notice {
        background-color: rgba(242, 225, 204, 1);
        color: rgba(192, 116, 24, 1);
        border: none;
      }

      &.upgrade-notice {
        background-color: rgba(230, 247, 255, 1);
        color: rgba(24, 144, 255, 1);
        border: none;
      }

      &.default-notice {
        background-color: #f6f6f6;
        color: #666;
        border: 1px solid #d9d9d9;
      }
    }

    .dialog-message-content {
      flex: 1;

      .dialog-message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .dialog-message-time {
          font-size: 14px;
          color: rgba(25, 25, 25, 1);
        }
      }

      .dialog-message-title {
        font-size: 18px;
        font-weight: 600;
        color: rgba(25, 25, 25, 1);
        margin: 0 0 16px 0;
        line-height: 1.5;
      }

      .dialog-message-full-content {
        font-size: 14px;
        line-height: 1.8;
        color: #606266;

        :deep(p) {
          margin-bottom: 16px;

          &:last-child {
            margin-bottom: 0;
          }
        }

        :deep(a) {
          color: #409eff;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }

        :deep(br) {
          line-height: 1.8;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: end;
  align-items: center;

  .nav-buttons {
    display: flex;

    .el-button {
      padding: 5px 17px 5px 16px;
    }
  }
}
</style>
